package cn.gov.msa.ws;

import java.util.List;

import org.springframework.context.ApplicationContext;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;

import cn.gov.msa.model.Repository;
import cn.gov.msa.model.Reserve;
import cn.gov.msa.util.GsonHelper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class RepositoryService {

	public static String selectData(ApplicationContext ctx, String params) throws Exception {
		String result = "";
	    JSONObject jsonResult = new JSONObject();
	    cn.gov.msa.service.RepositoryService repositoryService = (cn.gov.msa.service.RepositoryService) ctx.getBean("RepositoryService");  				        
		JSONObject jsonParams = JSONObject.fromObject(params);
		int pageNum = 1;
		int pageSize = 10;
		if(jsonParams.has("pageNum"))
		{
			pageNum = jsonParams.getInt("pageNum");
			jsonParams.remove("pageNum");
		}
		if(jsonParams.has("pageSize"))
		{
			pageSize = jsonParams.getInt("pageSize");
			jsonParams.remove("pageSize");
		}	
		Repository repository = GsonHelper.convertEntity(jsonParams.toString(), Repository.class);
		List<Repository> repositoryList=repositoryService.selectRepository(pageNum, pageSize, repository);
	    JSONArray jaResult = JSONArray.fromObject(repositoryList);
	    //获取分页信息
        PageInfo page = new PageInfo(repositoryList);
        
        jsonResult.put("total", page.getTotal());
		jsonResult.put("rows", jaResult);	
		
		return jsonResult.toString();
	}
	
	public static String addViewCount(ApplicationContext ctx, String params) throws Exception {
		int result = 0;
		String info = "";
	    boolean save = false;
	    JSONObject jsonResult = new JSONObject();
	    cn.gov.msa.service.RepositoryService repositoryService = (cn.gov.msa.service.RepositoryService) ctx.getBean("RepositoryService");  				        
		JSONObject jsonParams = JSONObject.fromObject(params); 	
	    
	    try{
	    	Repository repository = GsonHelper.convertEntity(jsonParams.toString(), Repository.class);
	    	save=repositoryService.updateViewCount(repository);	
	    }
	    catch(Exception e){
	    	e.printStackTrace();
	    	result = 2;
	    	info = "数据保存异常！";
	    }
	    
	    if(save){
	    	result = 1;
	    	info = "数据保存成功！";
	    }
	    else{
	    	result = 0;
	    	info = "数据保存失败！";
	    }
	    

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);
	    
		return jsonResult.toString();
	}
}
